﻿using CaseManagerLibrary.Http;
using CaseManagerLibrary.Models;
using PSDLib;
using PSDLib.Models;
using PSDManager.SystemSettings;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Linq;
using Newtonsoft.Json;
using PSDManager.CreateTask;
using PSDLib.Protocols;

namespace PSDManager
{
    public partial class FrmManager : Form
    {
        private EventHandler updatePSDTree;
        private UpdateDownloadingFilesEventHandler updateDownloadingFiles;
        private UpdateBurnRuntimeEventHandler updateBurnRuntime;

        private ManagerHelper managerHelper;


        private TreeNode currTaskNode;

        private IDataPanel currentDataPanel;

        public PSDState CurrPSD
        {
            get { return managerHelper.CurrPSD; }
            set
            {
                bool changed = false;
                if (managerHelper.CurrPSD == null)
                {
                    changed = true;
                }
                else if (value == null)
                {
                    changed = false;
                }
                else
                {
                    changed = (managerHelper.CurrPSD.DeviceId != value.DeviceId);
                }

                managerHelper.CurrPSD = value;

                RefreshPSDDeviceInfo(managerHelper.CurrPSD, changed);

                EnablePSDDevice((managerHelper.CurrPSD == null ? false : managerHelper.CurrPSD.Online));
            }
        }

        public FrmManager()
        {
            InitializeComponent();

            this.WindowState = FormWindowState.Maximized;

            tvwPSD.Nodes.Clear();
            tvwTask.Nodes.Clear();

            managerHelper = new ManagerHelper();
            managerHelper.OnAddPSD += ManagerHelper_OnAddPSD;
            managerHelper.OnAddPSDTask += ManagerHelper_OnAddPSDTask;
            managerHelper.OnUpdateDownloadingFiles += ManagerHelper_OnUpdateDownloadingFiles;
            managerHelper.OnUpdateBurnRuntime += ManagerHelper_OnUpdateBurnRuntime;

            this.psdClientDevice1.ManagerHelper = managerHelper;

            this.Shown += FrmManager_Shown;
            this.FormClosing += FrmManager_FormClosing;
            this.tvwPSD.AfterSelect += TvwPSD_AfterSelect;
            this.tvwTask.AfterSelect += TvwTask_AfterSelect;
            this.tabDL.SelectedIndexChanged += TabControl1_SelectedIndexChanged;

            this.taskInfoPanel.ManagerHelper = managerHelper;
            this.taskInfoPanel.OnDownloadStateChanged += TaskInfoPanel_OnDownloadStateChanged;

            this.downloadingFilesPanel.ManagerHelper = managerHelper;

            this.dlpWait.ManagerHelper = managerHelper;
            this.dlpWait.ShowListCheckBox = false;
            this.dlpWait.FileState = new int[] { -1 };
            this.dlpWait.OnUpdateSummary += DlpWait_OnUpdateSummary;
            this.dlpWait.AddCustomAction("刷新", Properties.Resources.refresh, (ToolStripButton btn, ListView list) =>
            {
                UpdateCurrentDataPanel();
            });

            this.dlpSuccess.ManagerHelper = managerHelper;
            this.dlpSuccess.ShowListCheckBox = false;
            this.dlpSuccess.FileState = new int[] { 1 };
            this.dlpSuccess.OnUpdateSummary += DlpSuccess_OnUpdateSummary;
            this.dlpSuccess.AddCustomAction("刷新", Properties.Resources.refresh, (ToolStripButton btn, ListView list) =>
            {
                UpdateCurrentDataPanel();
            });

            this.dlpFail.ManagerHelper = managerHelper;
            this.dlpFail.ShowListCheckBox = true;
            this.dlpFail.FileState = new int[] { 2 };
            this.dlpFail.OnUpdateSummary += DlpFail_OnUpdateSummary;
            this.dlpFail.AddCustomAction("刷新", Properties.Resources.refresh, (ToolStripButton btn, ListView list) =>
            {
                UpdateCurrentDataPanel();
            });
            this.dlpFail.AddCustomAction("忽略错误", Properties.Resources.ignore, IgnoreFail);
            this.dlpFail.AddCustomAction("重新下载", Properties.Resources.start_dl, ReDownloadFile);
            this.dlpFail.AddCustomAction("全部选择", Properties.Resources.select, SelectAllFailFile);

            this.taskHistoryPanel.ManagerHelper = managerHelper;
            this.taskHistoryPanel.ShowListCheckBox = false;
            this.taskHistoryPanel.Summary = "";
            this.taskHistoryPanel.AddCustomAction("刷新", Properties.Resources.refresh, (ToolStripButton btn, ListView list) =>
            {
                UpdateCurrentDataPanel();
            });
            this.taskHistoryPanel.AddCustomAction("刻录光盘", Properties.Resources.burn_6, (ToolStripButton btn, ListView list) =>
            {
                if (list.SelectedItems.Count > 0)
                {
                    CreateBurnTask((list.SelectedItems[0].Tag as dl_task));
                }
            }, false);

            this.burnTaskPanel.ManagerHelper = managerHelper;

            this.dlpCaseLog.ManagerHelper = managerHelper;
            this.dlpCaseLog.ShowListCheckBox = false;
            this.dlpCaseLog.AddCustomAction("刷新", Properties.Resources.refresh, (ToolStripButton btn, ListView list) =>
            {
                UpdateCurrentDataPanel();
            });
            this.dlpCaseLog.AddCustomAction("立即下载", Properties.Resources.start_dl, DownloadLogImmediate);

            this.toolTip1.SetToolTip(pbRefreshPSD, "刷新设备");

            this.toolTip1.SetToolTip(pbStartDL, "开始下载");
            this.toolTip1.SetToolTip(pbStopDL, "暂停下载");
            this.toolTip1.SetToolTip(pbFinishDL, "结束下载");
            this.toolTip1.SetToolTip(pbDeleteDL, "删除下载");

            EnablePSDDevice(false);
            ResetDataPanels(true);
            currentDataPanel = taskInfoPanel;

            updatePSDTree = new EventHandler(delegate (object sender, EventArgs e)
            {
                EnablePSDDevice(false);

                //ResetDataPanels(true);

                tvwPSD.Nodes.Clear();
                List<PSDState> psdList = (List<PSDState>)sender;

                psdList.Sort();

                foreach (var psd in psdList)
                {
                    TreeNode node = new TreeNode();
                    node.Text = psd.DeviceInfo.device_name;
                    node.Name = psd.DeviceId;
                    node.Tag = psd;
                    node.ImageIndex = (psd.Online ? 0 : 1);
                    node.SelectedImageIndex = (psd.Online ? 0 : 1);
                    tvwPSD.Nodes.Add(node);
                }

                if (CurrPSD != null)
                {
                    var curr_node = tvwPSD.Nodes.Find(CurrPSD.DeviceId, false);
                    if (curr_node.Length > 0)
                    {
                        CurrPSD = curr_node[0].Tag as PSDState;
                        tvwPSD.SelectedNode = curr_node[0];
                    }
                    else
                    {
                        CurrPSD = null;
                    }
                }
                else
                {
                    if (tvwPSD.Nodes.Count > 0)
                    {
                        tvwPSD.SelectedNode = tvwPSD.Nodes[0];
                        CurrPSD = tvwPSD.SelectedNode.Tag as PSDState;
                    }
                }
            });

            updateDownloadingFiles = new UpdateDownloadingFilesEventHandler(delegate (List<dl_files> files)
            {
                downloadingFilesPanel.UpdateDataPanel(files);
            });

            updateBurnRuntime = new UpdateBurnRuntimeEventHandler(delegate (BurnRuntime runtime)
            {
                burnTaskPanel.UpdateBurnRuntime(runtime);
            });
        }

        protected override void CreateHandle()
        {
            if (!IsHandleCreated)
            {
                try
                {
                    base.CreateHandle();
                }
                catch { }
                finally
                {
                    if (!IsHandleCreated)
                    {
                        base.RecreateHandle();
                    }
                }
            }
        }

        private void TaskInfoPanel_OnDownloadStateChanged(object sender, EventArgs e)
        {
            this.btnRefreshDevice.PerformClick();
        }

        private void IgnoreFail(ToolStripButton sender, ListView listview)
        {
            if (CurrPSD != null)
            {
                List<string> ignoreList = new List<string>();

                for (int i = listview.CheckedItems.Count - 1; i >= 0; i--)
                {
                    var file = listview.CheckedItems[i].Tag as dl_files;

                    ignoreList.Add(file.id);

                    listview.CheckedItems[i].Remove();
                }

                if (ignoreList.Count > 0)
                {
                    managerHelper.IgnoreFail(CurrPSD.DeviceId, ignoreList);
                }
            }
        }

        private void ReDownloadFile(ToolStripButton sender, ListView listview)
        {
            if (CurrPSD != null)
            {
                for (int i = listview.CheckedItems.Count - 1; i >= 0; i--)
                {
                    var file = listview.CheckedItems[i].Tag as dl_files;

                    managerHelper.ReDownloadFile(CurrPSD.DeviceId, file.id);

                    listview.CheckedItems[i].Remove();
                }
            }
        }

        private void SelectAllFailFile(ToolStripButton sender, ListView listview)
        {
            foreach (ListViewItem item in listview.Items)
            {
                item.Checked = (sender.Text == "全部选择");
            }

            sender.Text = sender.Text == "全部选择" ? "全部取消" : "全部选择";
            sender.Image = sender.Text == "全部选择" ? Properties.Resources.select : Properties.Resources.unselect;
        }

        private void DownloadLogImmediate(ToolStripButton sender, ListView listview)
        {
            if (CurrPSD != null)
            {
                managerHelper.DownloadLogImmediate(CurrPSD.DeviceId);
            }
        }

        private void TabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabDL.SelectedTab.Controls.Count > 0)
            {
                currentDataPanel = (tabDL.SelectedTab.Controls[0] as IDataPanel);

                UpdateCurrentDataPanel();
            }
            else
            {
                currentDataPanel = null;
            }
        }

        //private void DlpDownloading_OnUpdateSummary(dl_task task, dl_task_channel channel, int fileCount)
        //{
        //    string room = (task == null ? "" : "留置室：" + task.room_num);

        //    string file = "当前正在下载文件：" + fileCount.ToString() + " 个";

        //    dlpDownloading.Summary = room + "    " + file;
        //}
        private void DlpWait_OnUpdateSummary(dl_task task, dl_task_channel channel, int fileCount)
        {
            string room = (task == null ? "" : task.task_name);

            string file = "等待下载文件：" + fileCount.ToString() + " 个";

            dlpSuccess.Summary = room + "    " + file;
        }

        private void DlpSuccess_OnUpdateSummary(dl_task task, dl_task_channel channel, int fileCount)
        {
            string room = (task == null ? "" : task.task_name);

            string file = "已成功下载文件：" + fileCount.ToString() + " 个";

            dlpSuccess.Summary = room + "    " + file;
        }

        private void DlpFail_OnUpdateSummary(dl_task task, dl_task_channel channel, int fileCount)
        {
            string room = (task == null ? "" : task.task_name);

            string file = "下载文件失败：" + fileCount.ToString() + " 个";

            dlpFail.Summary = room + "    " + file;
        }

        private void FrmManager_Shown(object sender, EventArgs e)
        {
            if (AppSettings.Enabled)
            {
                managerHelper.OpenManager();

                //psdClientDevice1.GetDownloadServer();
            }
        }

        private void FrmManager_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (AppSettings.Enabled)
            {
                managerHelper.CloseManager();
            }
        }

        private void ResetDataPanels(bool immediate)
        {
            taskInfoPanel.Reset(immediate);
            downloadingFilesPanel.Reset(immediate);
            dlpWait.Reset(immediate);
            dlpSuccess.Reset(immediate);
            dlpFail.Reset(immediate);
        }
        /// <summary>
        /// 根据当前选中的任务节点，更新任务下载功能按钮状态
        /// </summary>
        private void UpdateDLButtons()
        {
            if (tvwTask.SelectedNode == null)
            {
                pbStartDL.Image = Properties.Resources.start_dl_disable;
                pbStartDL.Enabled = false;
                pbStopDL.Image = Properties.Resources.stop_dl_disable;
                pbStopDL.Enabled = false;
                pbFinishDL.Image = Properties.Resources.finish_dl_disable;
                pbFinishDL.Enabled = false;
                pbDeleteDL.Image = Properties.Resources.delete_dl_disable;
                pbDeleteDL.Enabled = false;
            }
            else
            {
                object obj = tvwTask.SelectedNode.Tag;
                int state = 0;
                if (obj.GetType() == typeof(dl_task))
                {
                    state = (obj as dl_task).download_state;
                }
                else if (obj.GetType() == typeof(dl_task_channel))
                {
                    state = (obj as dl_task_channel).download_state;
                }

                pbStartDL.Image = (state == 0 ? Properties.Resources.start_dl : Properties.Resources.start_dl_disable);
                pbStartDL.Enabled = (state == 0);
                pbStopDL.Image = (state == 1 ? Properties.Resources.stop_dl : Properties.Resources.stop_dl_disable);
                pbStopDL.Enabled = (state == 1);
                pbFinishDL.Image = (state < 2 ? Properties.Resources.finish_dl : Properties.Resources.finish_dl_disable);
                pbFinishDL.Enabled = (state < 2);
                pbDeleteDL.Image = Properties.Resources.delete_dl;
                pbDeleteDL.Enabled = true;
            }
        }

        /// <summary>
        /// 更新当前选中数据面板内容
        /// </summary>
        private void UpdateCurrentDataPanel()
        {
            try
            {
                if (currTaskNode == null)
                {
                    currTaskNode = tvwTask.SelectedNode;
                }
                else
                {
                    if (tvwTask.SelectedNode != null)
                    {
                        if (currTaskNode.Name != tvwTask.SelectedNode.Name)
                        {
                            currTaskNode = tvwTask.SelectedNode;
                        }
                    }
                    else
                    {
                        currTaskNode = null;
                    }
                }

                if (currTaskNode != null)
                {
                    dl_task task;
                    dl_task_channel channel;

                    if (currTaskNode.Level == 0)
                    {
                        task = (currTaskNode.Tag as dl_task);
                        channel = null;
                    }
                    else
                    {
                        task = (currTaskNode.Parent.Tag as dl_task);
                        channel = (currTaskNode.Tag as dl_task_channel);
                    }

                    //UpdateDLSummary(task);
                    if (currentDataPanel != null)
                    {
                        currentDataPanel.RefreshData(task, channel, managerHelper);
                    }
                }
                else
                {
                    currentDataPanel.Reset(true);
                }
            }
            catch { }
        }

        ///// <summary>
        ///// 根据当前选中的任务节点，更新任务概况信息
        ///// </summary>
        ///// <param name="task"></param>
        //private void UpdateDLSummary(dl_task task)
        //{
        //    //if (task != null)
        //    //{

        //    //    lblRoomNum.Text = task.room_num;
        //    //    lblDLStartTime.Text = task.start_time.ToString("yyyy-MM-dd HH:mm:ss");
        //    //    lblDLSuccess.Text = task.file_count.ToString() + "个";
        //    //    lblDLFail.Text = task.error_count.ToString() + "个";
        //    //}
        //    //else
        //    //{
        //    //    lblRoomNum.Text = "--";
        //    //    lblDLStartTime.Text = "--";
        //    //    lblDLSuccess.Text = "--个";
        //    //    lblDLFail.Text = "--个";
        //    //}
        //}

        /// <summary>
        /// 设置任务节点显示内容
        /// </summary>
        /// <param name="node"></param>
        /// <param name="task"></param>
        private void UpdateTaskNode(TreeNode node, dl_task task)
        {
            node.Text = task.task_name;
            node.Name = task.id;
            node.Tag = task;
            node.ImageIndex = task.download_state;
            node.SelectedImageIndex = task.download_state;
        }

        /// <summary>
        /// 设置通道节点显示内容
        /// </summary>
        /// <param name="node"></param>
        /// <param name="channel"></param>
        private void UpdateChannelNode(TreeNode node, dl_task_channel channel)
        {
            node.Text = channel.channel_name;
            node.Name = channel.id;
            node.Tag = channel;
            node.ImageIndex = channel.download_state + 3;
            node.SelectedImageIndex = channel.download_state + 3;
        }

        /// <summary>
        /// 根据PSD设备可用状态,设置相关功能按钮可用状态
        /// </summary>
        /// <param name="psdEnable"></param>
        private void EnablePSDDevice(bool psdEnable)
        {
            this.btnRefreshDevice.Enabled = psdEnable;
            this.btnAddDLTask.Enabled = psdEnable;
            this.toolStrip1.Enabled = psdEnable;
            this.btnAddBurnTask.Enabled = psdEnable;
            this.btnTalkVideo.Enabled = psdEnable;
            this.pbStartDL.Enabled = psdEnable;
            this.pbStartDL.Image = (psdEnable ? Properties.Resources.start_dl : Properties.Resources.start_dl_disable);
            this.pbStopDL.Enabled = psdEnable;
            this.pbStopDL.Image = (psdEnable ? Properties.Resources.stop_dl : Properties.Resources.stop_dl_disable);
            this.pbFinishDL.Enabled = psdEnable;
            this.pbFinishDL.Image = (psdEnable ? Properties.Resources.finish_dl : Properties.Resources.finish_dl_disable);
            this.pbDeleteDL.Enabled = psdEnable;
            this.pbDeleteDL.Image = (psdEnable ? Properties.Resources.delete_dl : Properties.Resources.delete_dl_disable);
            this.psdClientDevice1.Enabled = psdEnable;
        }

        /// <summary>
        /// PDM获取PSD设备列表后，更新UI界面的事件
        /// </summary>
        /// <param name="psdList"></param>
        private void ManagerHelper_OnAddPSD(List<PSDState> psdList)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(updatePSDTree, psdList, null);
            }
            else
            {
                updatePSDTree(psdList, null);
            }
        }

        /// <summary>
        /// PSD树选择事件
        /// 选择对应PSD设备节点后，刷新PSD信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TvwPSD_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                CurrPSD = e.Node.Tag as PSDState;

                //RefreshPSDDeviceInfo(CurrPSD);
            }
        }

        /// <summary>
        /// 刷新指定PSD设备信息
        /// </summary>
        /// <param name="ps"></param>
        private void RefreshPSDDeviceInfo(PSDState ps, bool changed)
        {
            if (changed)
            {
                ResetDataPanels(true);
            }

            if (ps != null)
            {
                psdClientDevice1.SetDevice(ps);

                if (changed)
                {
                    if (ps.DeviceInfo.device_version == "PSD Pro")
                    {
                        tabBurning.Parent = tabDL;
                        //tabBurnSuccess.Parent = tabDL;
                        //tabBurnFailed.Parent = tabDL;
                    }
                    else
                    {
                        tabBurning.Parent = null;
                        //tabBurnSuccess.Parent = null;
                        //tabBurnFailed.Parent = null;
                    }

                    EnablePSDDevice(ps.Online);
                    tvwTask.Nodes.Clear();
                    managerHelper.GetPSDTask(ps.DeviceId);
                }
            }
        }

        /// <summary>
        /// PDM获取PSD任务数据后，更新UI界面的事件
        /// 在界面的树形控件中添加任务节点和其关联的通道节点
        /// </summary>
        /// <param name="task"></param>
        /// <param name="channels"></param>
        private void ManagerHelper_OnAddPSDTask(List<DownloadTask> dtList)
        {
            for (int i = tvwTask.Nodes.Count - 1; i >= 0; i--)
            {
                if (dtList.Where(t => t.Task.id == (tvwTask.Nodes[i].Tag as dl_task).id).FirstOrDefault() == null)
                {
                    tvwTask.Nodes[i].Remove();
                }
            }

            foreach (var dt in dtList)
            {
                var node = tvwTask.Nodes.Find(dt.Task.id, false);
                TreeNode node_task;
                if (node.Length == 0)
                {
                    node_task = new TreeNode();
                    tvwTask.Nodes.Add(node_task);
                }
                else
                {
                    node_task = node[0];
                }

                UpdateTaskNode(node_task, dt.Task);

                for (int i = node_task.Nodes.Count - 1; i >= 0; i--)
                {
                    if (dt.ChannelList.Where(t => t.id == (node_task.Nodes[i].Tag as dl_task_channel).id).FirstOrDefault() == null)
                    {
                        node_task.Nodes[i].Remove();
                    }
                }

                foreach (var ch in dt.ChannelList)
                {
                    node = node_task.Nodes.Find(ch.id, false);
                    TreeNode node_ch;
                    if (node.Length == 0)
                    {
                        node_ch = new TreeNode();
                        node_task.Nodes.Add(node_ch);
                    }
                    else
                    {
                        node_ch = node[0];
                    }

                    UpdateChannelNode(node_ch, ch);
                }
            }

            if (tvwTask.Nodes.Count > 0)
            {
                if (tvwTask.SelectedNode == null)
                {
                    tvwTask.SelectedNode = tvwTask.Nodes[0];
                }
            }
            else
            {
                ResetDataPanels(true);
            }

            tvwTask.ExpandAll();
        }

        private void ManagerHelper_OnUpdateDownloadingFiles(List<dl_files> files)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(updateDownloadingFiles, files);
            }
            else
            {
                updateDownloadingFiles(files);
            }
        }

        private void ManagerHelper_OnUpdateBurnRuntime(BurnRuntime runtime)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(updateBurnRuntime, runtime);
            }
            else
            {
                updateBurnRuntime(runtime);
            }
        }

        /// <summary>
        /// 任务树选择事件
        /// 选择对应节点后，更新功能按钮状态，下载任务概况、刷新下载任务明细
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TvwTask_AfterSelect(object sender, TreeViewEventArgs e)
        {
            UpdateDLButtons();

            UpdateCurrentDataPanel();
        }



        /// <summary>
        /// 刷新当前PSD设备信息按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefreshDevice_Click(object sender, EventArgs e)
        {
            if (tvwPSD.SelectedNode != null)
            {
                CurrPSD = null;
                CurrPSD = tvwPSD.SelectedNode.Tag as PSDState;
                RefreshPSDDeviceInfo(CurrPSD, true);
            }
        }

        /// <summary>
        /// 创建下载任务按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddDLTask_Click(object sender, EventArgs e)
        {
            //CreateDownloadTask(0);
            this.tsdbCreateTask.ShowDropDown();
        }

        /// <summary>
        /// 创建刻录任务按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddBurnTask_Click(object sender, EventArgs e)
        {

        }

        private void btnTalkVideo_Click(object sender, EventArgs e)
        {
            CreateDownloadTask(1);
        }

        private void CreateDownloadTask(int taskType)
        {
            FrmAddTask frm = new FrmAddTask(taskType);

            if (frm.ShowDialog() == DialogResult.OK)
            {
                foreach (var room in frm.SelectedRooms)
                {
                    dl_task_start start = new dl_task_start();
                    start.deviceId = CurrPSD.DeviceId;
                    start.roomNum = room.room_number;
                    start.startTime = frm.StartTime.Value;
                    start.endTime = frm.EndTime;
                    start.state = (int)DownloadTaskSate.暂停下载;
                    start.taskType = (frm.chkCaseOnly.Checked == false && taskType == 0) ? Convert.ToInt32(DownloadTaskCreateType.自定义时段) : taskType;
                    start.extendTime = frm.ExtendTime;
                    start.createType = 0;
                    start.currentCase = frm.chkCaseOnly.Checked ? 1 : 0;

                    var ret = managerHelper.CreateDownloadTask(start);

                    if (ret.success && ret.data != null)
                    {
                        var node_task = new TreeNode();
                        node_task.Text = ret.data.Task.task_name;
                        node_task.Name = ret.data.Task.id;
                        node_task.ImageIndex = ret.data.Task.download_state;
                        node_task.SelectedImageIndex = ret.data.Task.download_state;
                        node_task.Tag = ret.data.Task;
                        tvwTask.Nodes.Add(node_task);

                        foreach (var ch in ret.data.ChannelList)
                        {
                            TreeNode node_ch = new TreeNode();
                            node_ch.Text = ch.channel_name;
                            node_ch.Name = ch.id;
                            node_ch.ImageIndex = ch.download_state + 3;
                            node_ch.SelectedImageIndex = ch.download_state + 3;
                            node_ch.Tag = ch;
                            node_task.Nodes.Add(node_ch);
                        }
                    }
                    else
                    {
                        MessageBox.Show("下载任务创建失败：" + ret.message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }

                tvwTask.ExpandAll();
            }
        }

        private void CreateBurnTask(dl_task downloadTask)
        {
            FrmAddBurn frm = new FrmAddBurn();
            frm.StartPosition = FormStartPosition.CenterParent;
            frm.GetDownloadTaskData(downloadTask);

            if (frm.ShowDialog() == DialogResult.OK)
            {
                var ret = managerHelper.CreateBurnTask(frm.BurnTask);

                if (ret.success)
                {

                }
                else
                {
                    MessageBox.Show("刻录任务创建失败：" + ret.message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// 开始下载按钮事件
        /// 向PSD设备发送开始下载的消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pbStartDL_Click(object sender, EventArgs e)
        {
            if (this.tvwTask.SelectedNode != null)
            {
                TreeNode node_task = null;

                if (this.tvwTask.SelectedNode.Level == 0)
                {
                    node_task = tvwTask.SelectedNode;
                }
                else if (this.tvwTask.SelectedNode.Level == 1)
                {
                    node_task = tvwTask.SelectedNode.Parent;
                    //var task = this.tvwTask.SelectedNode.Parent.Tag as dl_task;
                    //task.download_state = (int)DownloadTaskSate.开始下载;
                    //UpdateTaskNode(this.tvwTask.SelectedNode.Parent, task);

                    //var ch = this.tvwTask.SelectedNode.Tag as dl_task_channel;
                    //ch.download_state = (int)DownloadTaskSate.开始下载;
                    //UpdateChannelNode(this.tvwTask.SelectedNode, ch);
                    //var channels = new List<dl_task_channel>();
                    //channels.Add(ch);

                    //managerHelper.StartPSDDownload(task.download_device_id, task, channels);
                }

                var task = node_task.Tag as dl_task;
                task.download_state = (int)DownloadTaskSate.开始下载;
                UpdateTaskNode(node_task, task);

                var channels = new List<dl_task_channel>();
                foreach (TreeNode node in node_task.Nodes)
                {
                    var ch = node.Tag as dl_task_channel;
                    ch.download_state = (int)DownloadTaskSate.开始下载;
                    channels.Add(ch);

                    UpdateChannelNode(node, ch);
                }

                managerHelper.StartPSDDownload(task.download_device_id, task, channels);

                btnRefreshDevice.PerformClick();
            }
        }

        /// <summary>
        /// 暂停下载按钮事件
        /// 向PSD设备发送暂停下载的消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pbStopDL_Click(object sender, EventArgs e)
        {
            if (this.tvwTask.SelectedNode != null)
            {
                TreeNode node_task = null;

                if (this.tvwTask.SelectedNode.Level == 0)
                {
                    node_task = tvwTask.SelectedNode;
                }
                else if (this.tvwTask.SelectedNode.Level == 1)
                {
                    node_task = tvwTask.SelectedNode.Parent;
                    //var task = this.tvwTask.SelectedNode.Parent.Tag as dl_task;
                    ////task.download_state = (int)DownloadTaskSate.暂停下载;
                    ////UpdateTaskNode(this.tvwTask.SelectedNode.Parent, task);

                    //var ch = this.tvwTask.SelectedNode.Tag as dl_task_channel;
                    //ch.download_state = (int)DownloadTaskSate.暂停下载;
                    //UpdateChannelNode(this.tvwTask.SelectedNode, ch);
                    //var channels = new List<dl_task_channel>();
                    //channels.Add(ch);

                    //managerHelper.StopPSDDownload(task.download_device_id, task, channels);
                }

                var task = node_task.Tag as dl_task;
                task.download_state = (int)DownloadTaskSate.暂停下载;
                UpdateTaskNode(node_task, task);

                var channels = new List<dl_task_channel>();
                foreach (TreeNode node in node_task.Nodes)
                {
                    var ch = node.Tag as dl_task_channel;
                    ch.download_state = (int)DownloadTaskSate.暂停下载;
                    channels.Add(ch);

                    UpdateChannelNode(node, ch);
                }

                managerHelper.StopPSDDownload(task.download_device_id, task, channels);

                btnRefreshDevice.PerformClick();
            }
        }

        private void pbFinishDL_Click(object sender, EventArgs e)
        {
            if (this.tvwTask.SelectedNode != null)
            {

                TreeNode node_task = null;

                if (this.tvwTask.SelectedNode.Level == 0)
                {
                    node_task = tvwTask.SelectedNode;
                }
                else if (this.tvwTask.SelectedNode.Level == 1)
                {
                    node_task = tvwTask.SelectedNode.Parent;
                }

                var task = node_task.Tag as dl_task;

                if (MessageBox.Show("是否确定结束 " + task.room_num + " 的下载任务", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    task.download_state = (int)DownloadTaskSate.结束下载;
                    UpdateTaskNode(node_task, task);

                    var channels = new List<dl_task_channel>();
                    foreach (TreeNode node in node_task.Nodes)
                    {
                        var ch = node.Tag as dl_task_channel;
                        ch.download_state = (int)DownloadTaskSate.结束下载;
                        channels.Add(ch);

                        UpdateChannelNode(node, ch);
                    }

                    managerHelper.FinishPSDDownload(task.download_device_id, task, channels);

                    btnRefreshDevice.PerformClick();
                }
            }
        }

        private void pbDeleteDL_Click(object sender, EventArgs e)
        {
            if (this.tvwTask.SelectedNode != null)
            {
                TreeNode node_task = null;

                if (this.tvwTask.SelectedNode.Level == 0)
                {
                    node_task = tvwTask.SelectedNode;
                }
                else if (this.tvwTask.SelectedNode.Level == 1)
                {
                    node_task = tvwTask.SelectedNode.Parent;
                }

                var task = node_task.Tag as dl_task;

                if (MessageBox.Show("是否确定删除 " + task.room_num + " 的下载任务", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    task.download_state = (int)DownloadTaskSate.暂停下载;
                    UpdateTaskNode(node_task, task);

                    var channels = new List<dl_task_channel>();
                    foreach (TreeNode node in node_task.Nodes)
                    {
                        var ch = node.Tag as dl_task_channel;
                        ch.download_state = (int)DownloadTaskSate.暂停下载;
                        channels.Add(ch);

                        UpdateChannelNode(node, ch);
                    }

                    managerHelper.DeletePSDDownload(task.download_device_id, task, channels);

                    node_task.Remove();

                    btnRefreshDevice.PerformClick();
                }
            }
        }

        private void pbSettings_Click(object sender, EventArgs e)
        {
            OpenSettings();
        }

        private void lblSettings_Click(object sender, EventArgs e)
        {
            OpenSettings();
        }

        private void OpenSettings()
        {
            FrmSettings frm = new FrmSettings();
            frm.ManagerHelper = managerHelper;
            frm.StartPosition = FormStartPosition.CenterParent;
            frm.ShowDialog();
        }

        private void pbRefreshPSD_Click(object sender, EventArgs e)
        {
            managerHelper.RefreshPSDList();
        }

        private void tsmiDailyTask_Click(object sender, EventArgs e)
        {
            CreateDownloadTask(Convert.ToInt32(DownloadTaskCreateType.常规Routine));
        }

        private void tsmiCameraSDTask_Click(object sender, EventArgs e)
        {
            FrmAddTaskForCameraSD frm = new FrmAddTaskForCameraSD();

            if (frm.ShowDialog() == DialogResult.OK)
            {
                foreach (var start in frm.TaskStart)
                {
                    start.deviceId = CurrPSD.DeviceId;

                    var result = managerHelper.CreateDownloadTaskCameraSD(start);

                    if (!result.success)
                    {
                        MessageBox.Show(start.roomNum + "下载任务创建失败：" + result.message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }

                this.btnRefreshDevice.PerformClick();
            }
        }

        private void tsmiCustomTask_Click(object sender, EventArgs e)
        {
            CreateDownloadTask(Convert.ToInt32(DownloadTaskCreateType.自定义时段));
        }

        private void tsmiEntryTask_Click(object sender, EventArgs e)
        {
            FrmAddEntryTask frm = new FrmAddEntryTask();
            frm.StartPosition = FormStartPosition.CenterScreen;

            if (frm.ShowDialog() == DialogResult.OK)
            {
                var result = managerHelper.CreateDownloadEntryTask(frm.StartInfo);

                if (!result.success)
                {
                    MessageBox.Show("进点过程下载任务创建失败：" + result.message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                this.btnRefreshDevice.PerformClick();
            }
        }

        private void tsmiLeaveTask_Click(object sender, EventArgs e)
        {
            FrmAddLeaveTask frm = new FrmAddLeaveTask();
            frm.StartPosition = FormStartPosition.CenterScreen;

            if (frm.ShowDialog() == DialogResult.OK)
            {
                var result = managerHelper.CreateDownloadLeaveTask(frm.StartInfo);

                if (!result.success)
                {
                    MessageBox.Show("离点过程下载任务创建失败：" + result.message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                this.btnRefreshDevice.PerformClick();
            }
        }

        private void tsmiTalkOutTask_Click(object sender, EventArgs e)
        {
            FrmAddTalkOutTask frm = new FrmAddTalkOutTask("去程");
            frm.StartPosition = FormStartPosition.CenterScreen;

            if (frm.ShowDialog() == DialogResult.OK)
            {
                var result = managerHelper.CreateDownloadTalkOutTask(frm.StartInfo);

                if (!result.success)
                {
                    MessageBox.Show("外出谈话(去程)下载任务创建失败：" + result.message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                this.btnRefreshDevice.PerformClick();
            }
        }

        private void tsmiTalkBackTask_Click(object sender, EventArgs e)
        {
            FrmAddTalkOutTask frm = new FrmAddTalkOutTask("回程");
            frm.StartPosition = FormStartPosition.CenterScreen;

            if (frm.ShowDialog() == DialogResult.OK)
            {
                var result = managerHelper.CreateDownloadTalkBackTask(frm.StartInfo);

                if (!result.success)
                {
                    MessageBox.Show("外出谈话(回程)下载任务创建失败：" + result.message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                this.btnRefreshDevice.PerformClick();
            }
        }

        private void tsmiTalkTask_Click(object sender, EventArgs e)
        {
            FrmAddTalkTask frm = new FrmAddTalkTask();
            frm.StartPosition = FormStartPosition.CenterScreen;

            if (frm.ShowDialog() == DialogResult.OK)
            {
                var result = managerHelper.CreateDownloadTalkTask(frm.StartInfo);

                if (!result.success)
                {
                    MessageBox.Show("谈话过程下载任务创建失败：" + result.message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                this.btnRefreshDevice.PerformClick();
            }
        }

        private void tsmiChangeRoomTask_Click(object sender, EventArgs e)
        {
            FrmAddChangeRoomTask frm = new FrmAddChangeRoomTask();
            frm.StartPosition = FormStartPosition.CenterScreen;

            if (frm.ShowDialog() == DialogResult.OK)
            {
                if (frm.DailyTask)
                {
                    var result = managerHelper.CreateDownloadChangeRoomDailyTask(frm.StartInfo);

                    if (!result.success)
                    {
                        MessageBox.Show("换房下载任务创建失败：" + result.message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }

                if (frm.RouteTask)
                {
                    var result = managerHelper.CreateDownloadChangeRoomRouteTask(frm.StartInfo);

                    if (!result.success)
                    {
                        MessageBox.Show("换房过程下载任务创建失败：" + result.message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                this.btnRefreshDevice.PerformClick();
            }
        }

        private void tsmiRelieveTask_Click(object sender, EventArgs e)
        {
            FrmAddRelieveTask frm = new FrmAddRelieveTask();
            frm.StartPosition = FormStartPosition.CenterScreen;

            if (frm.ShowDialog() == DialogResult.OK)
            {
                var result = managerHelper.CreateDownloadRelieveTask(frm.StartInfo);

                if (!result.success)
                {
                    MessageBox.Show("放风过程下载任务创建失败：" + result.message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                this.btnRefreshDevice.PerformClick();
            }
        }


    }


}
